﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace CPPEI.WebApi
{
    /// <summary>
    /// 存放认证信息（使用asp.net form认证）
    /// </summary>
    public class FormsAuthProvider : IAuthProvider
    {
        public bool Save(string userId, TimeSpan expires)
        {
            string dataJsonString = userId;
            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.Add(expires), true, dataJsonString); //建立身份验证票对象 
            string ticketString = FormsAuthentication.Encrypt(ticket);
            //将加密后的票据保存为cookie 
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString);
            //这里的IsPersistent不会自己判断，需要手工判断，但FormsAuthenticationTicket的expiration的值是有过期性的，无论cookie的Expires设置多久，只要expiration到期，即使cookie存在用户验证也将失败
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            //使用加入了userdata的新cookie 
            HttpContext.Current.Response.Cookies.Add(cookie);
            return true;
        }

        public void Delete()
        {
            System.Web.Security.FormsAuthentication.SignOut();
        }

        public string GetUserId()
        {
            if (HttpContext.Current.User == null)
            {
                return null;
            }
            return HttpContext.Current.User.Identity.Name;
        }

        public bool IsAuth()
        {
            if (HttpContext.Current.User == null)
            {
                return false;
            }
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }
    }
}
